package com.gravata.enigma.importer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import com.gravata.enigma.FtpHelper;
import com.gravata.enigma.R;
import com.gravata.enigma.ReloadDataListener;
import com.gravata.enigma.activities.TelaInicial;
import com.gravata.enigma.model.FEC;
import com.gravata.enigma.model.Modulacao;
import com.gravata.enigma.model.Pilot;
import com.gravata.enigma.model.Polarization;
import com.gravata.enigma.model.Sistema;
import com.gravata.enigma.model.Transponder;

public class ParseSatInfo extends AsyncTask<String, String, Boolean> {

	private Context context;
	private ProgressDialog progress;
	private ReloadDataListener listener;
	private List<Sat> satelites=new ArrayList<Sat>();
	private final String URL="http://www.portaleds.com/gerar/imp.php?sat=%s&fil=td";
	public ParseSatInfo(Context context,List<Sat> satelites, ReloadDataListener listener){
		this.context=context;
		this.listener=listener;
		this.satelites=satelites;
	}

	@Override
	protected Boolean doInBackground(String... arg0) {

		for(Sat satelite:satelites){
			try {
				publishProgress(context.getString(R.string.gerando_satelites)+"\n\n"+ context.getString(R.string.carregando_dados_satelite)+": "+satelite.getNome());
				Document doc=Jsoup.connect(String.format(URL, Integer.toString(satelite.getPosicao()))).header("Accept-Encoding", "gzip, deflate")
					    .userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0")
					    .maxBodySize(0)
					    .timeout(600000)
					    .get();

				Elements divs=doc.select("div.limp:not(:empty)");

				for(Element linha: divs){

					Elements ps=linha.select("p");
					Element pFreq=ps.get(0);
					Element pBand=ps.get(1);
					Element pSistema=ps.get(2);
					Element pPais=ps.last();

					Transponder transponder=new Transponder();
					Elements t=pFreq.select("span");
					if(t.size()==0)
						continue;

					String [] tmp=t.first().text().trim().split("\\s");
					transponder.setFrequency(Integer.parseInt(tmp[0]+"000"));
					transponder.setPolarization(Polarization.getPorSigla(tmp[1]));

					pFreq.select("span").remove();
					tmp=pFreq.text().trim().replaceAll(",", "").split("\\s");
					if(tmp.length>1)
						transponder.setSymbolRate(Integer.parseInt(tmp[1]+"000"));


					transponder.setSystem(Sistema.getPorNome(pSistema.select("b").first().text().trim()));
					pSistema.select("b").remove();
					String strTmp=pSistema.text().trim().toLowerCase();

					if(strTmp.contains("piloto")){
						Matcher match= Pattern.compile("piloto\\s.{1,2}").matcher(strTmp);
						match.find();
						if(match.group().endsWith("on"))
							transponder.setPilot(Pilot.ON);
						else if(match.group().endsWith("off"))
							transponder.setPilot(Pilot.OFF);
						else
							transponder.setPilot(Pilot.AUTO);

					}

					if(strTmp.contains("fec")){
						Matcher match= Pattern.compile("fec\\s.{1,3}").matcher(strTmp);
						match.find();
						if(match.group().endsWith("?"))
							transponder.setFec(FEC.AUTO);
						else
							transponder.setFec(FEC.getPorNome(match.group().split("\\s")[1]));

					}

					strTmp=strTmp.replaceAll("piloto\\s.{1,2}", "");
					strTmp=strTmp.replaceAll("fec\\s.{1,3}", "");
					strTmp=strTmp.replace("-", "").trim();
					transponder.setModulation(Modulacao.getPorNome(strTmp));
					String banda=pBand.text().trim();
					if(!satelite.getTransponderBanda().containsKey(banda)){
						satelite.getTransponderBanda().put(banda, new HashMap<String, List<Transponder>>());
					}
					String pais=pPais.text().trim();
					if(!satelite.getTransponderBanda().get(banda).containsKey(pais)){
						satelite.getTransponderBanda().get(banda).put(pais, new ArrayList<Transponder>());
					}
					satelite.getTransponderBanda().get(banda).get(pais).add(transponder);

				}


			} catch (IOException e) {
				e.printStackTrace();
			}
			Log.d("Sat "+satelite.getNome(),Integer.toString(satelite.getTransponders().size()));
		}

		enviarSat();
		return true;

	}

	private void enviarSat(){
		publishProgress(context.getString(R.string.criando_arquivo_satelite));
		StringBuilder file=new StringBuilder();
		file.append("<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n"+
		"<!--\n"+
		"\tfile generated on "+(new Date())+"\n"+
		"\tby EasyBouquets Android  App - https://play.google.com/store/apps/details?id=com.gravata.enigma\n"+
		"\tall those information were extract from "+URL+"\n"+
		"\tplease let us know if you find any inconsistencies in this file\n"+
	    "-->\n"+
		"<satellites>\n");

		for(Sat sat: satelites){
			file.append("\n").append(sat.getStrSat());
		}
		file.append("\n</satellites>");

		FtpHelper ftp=new FtpHelper(context);
		publishProgress(context.getString(R.string.enviando_arquivo_satelite));
		try {
			ftp.send(TelaInicial.profile.getSatelitePath(), file.toString(),true);
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e1) {
			}
			publishProgress(context.getString(R.string.reiniciar));

		} catch (Exception e) {
			e.printStackTrace();
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e1) {
			}
			publishProgress(context.getString(R.string.ftp_error_conexao));

		}


	}

	@Override
	protected void onPreExecute() {
		progress = new ProgressDialog((Activity) context);
		// Cria novo um ProgressDialogo e exibe
		progress.setMessage(context.getString(R.string.ftp_conectando) + "...");
		progress.setCancelable(false);
		progress.show();
	}

	@Override
	protected void onProgressUpdate(String... values) {
		// Atualiza mensagem
		if (progress != null)
			progress.setMessage(values[0]);
	}

	@Override
	protected void onPostExecute(Boolean result) {
		progress.dismiss();
		listener.onReloadData();
	}


}